package com.sky.controller.admin;

import com.sky.dto.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.FinanceService;
import com.sky.vo.TransactionRecordVO;
import com.sky.vo.TransactionSummaryVO;
import com.sky.vo.WithdrawalVO;
import com.sky.vo.IdVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/finance")
@RequiredArgsConstructor
@Slf4j
public class FinanceController {

    private final FinanceService financeService;

    /**
     * 交易流水分页查询
     * @param dto 分页与筛选参数
     * @return 分页结果（总数与记录列表）
     */
    @GetMapping("/transaction/page")
    public Result<PageResult> getTransactionsPage(TransactionPageQueryDTO dto) {
        log.info("[transaction/page] params: {}", dto);
        PageResult page = financeService.getTransactionPage(dto);
        log.info("[transaction/page] total: {}", page.getTotal());
        return Result.success(page);
    }

    /**
     * 交易汇总统计
     * @param dto 查询参数（商家ID、时间范围等，可选）
     * @return 汇总视图对象（收入、支出、余额）
     */
    @GetMapping("/transaction/summary")
    public Result<TransactionSummaryVO> getTransactionsSummary(TransactionPageQueryDTO dto) {
        log.info("[transaction/summary] params: {}", dto);
        TransactionSummaryVO summary = financeService.getTransactionSummary(dto);
        log.info("[transaction/summary] result: income={}, expense={}, balance={}", summary.getTotalIncome(), summary.getTotalExpense(), summary.getBalance());
        return Result.success(summary);
    }

    /**
     * 新增调整流水
     * @param dto 调整参数
     * @return 新建记录ID
     */
    @PostMapping("/transaction/adjustment")
    public Result<IdVO> createAdjustment(@RequestBody AdjustmentCreateDTO dto) {
        log.info("[transaction/adjustment] body: {}", dto);
        IdVO idVO = financeService.createAdjustment(dto);
        log.info("[transaction/adjustment] created id: {}", idVO.getId());
        return Result.success(idVO);
    }

    /**
     * 提现申请分页查询
     * @param dto 分页与筛选参数
     * @return 分页结果
     */
    @GetMapping("/withdrawal/page")
    public Result<PageResult> getWithdrawalsPage(WithdrawalPageQueryDTO dto) {
        log.info("[withdrawal/page] params: {}", dto);
        PageResult page = financeService.getWithdrawalPage(dto);
        log.info("[withdrawal/page] total: {}", page.getTotal());
        return Result.success(page);
    }

    /**
     * 创建提现申请
     * @param dto 提现参数
     * @return 新建记录ID
     */
    @PostMapping("/withdrawal")
    public Result<IdVO> createWithdrawal(@RequestBody CreateWithdrawalDTO dto) {
        log.info("[withdrawal] body: {}", dto);
        IdVO idVO = financeService.createWithdrawal(dto);
        log.info("[withdrawal] created id: {}", idVO.getId());
        return Result.success(idVO);
    }

    /**
     * 审批通过提现申请
     * @param dto 审批参数，包含提现ID和实际打款金额（可选）
     * @return 操作结果字符串
     */
    @PostMapping("/withdrawal/approve")
    public Result<String> approveWithdrawal(@RequestBody ApproveWithdrawalDTO dto) {
        log.info("[withdrawal/approve] body: {}", dto);
        String res = financeService.approveWithdrawal(dto);
        log.info("[withdrawal/approve] result: {}", res);
        return Result.success(res);
    }

    /**
     * 拒绝提现申请
     * @param dto 拒绝参数，包含提现ID和原因
     * @return 操作结果字符串
     */
    @PostMapping("/withdrawal/reject")
    public Result<String> rejectWithdrawal(@RequestBody RejectWithdrawalDTO dto) {
        log.info("[withdrawal/reject] body: {}", dto);
        String res = financeService.rejectWithdrawal(dto);
        log.info("[withdrawal/reject] result: {}", res);
        return Result.success(res);
    }

    /**
     * 根据ID获取提现记录
     * @param id 提现记录ID
     * @return 提现视图对象
     */
    @GetMapping("/withdrawal/{id}")
    public Result<WithdrawalVO> getWithdrawalById(@PathVariable Long id) {
        log.info("[withdrawal/{id}] path id: {}", id);
        WithdrawalVO vo = financeService.getWithdrawalById(id);
        log.info("[withdrawal/{id}] found: {}", vo != null);
        return Result.success(vo);
    }

    /**
     * 导出财务数据为CSV
     * @param dto 查询参数（商户、方向、类别、时间范围等，可选）
     * @return CSV字节数组响应
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportFinanceData(TransactionPageQueryDTO dto) {
        log.info("[export] params: {}", dto);
        java.io.ByteArrayInputStream is = financeService.exportFinanceData(dto);
        byte[] bytes = new byte[is != null ? is.available() : 0];
        if (is != null) {
            is.read(bytes, 0, bytes.length);
        }
        log.info("[export] csv size(bytes): {}", (bytes == null ? 0 : bytes.length));
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=finance.csv");
        headers.add(HttpHeaders.CONTENT_TYPE, "text/csv; charset=utf-8");
        return ResponseEntity.ok().headers(headers).body(bytes);
    }
}